package com.ts.common.controller;

import com.alibaba.fastjson.JSON;
import com.ts.common.redis.RedisConstant;
import com.ts.common.redis.RedisUtil;
import com.ts.common.service.GeneratorService;
import com.ts.common.utils.GenUtils;
import com.ts.common.utils.Result;
import org.activiti.engine.impl.persistence.entity.ByteArrayEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/common/generator")
@Controller
public class GeneratorController {
    String prefix = "common/generator";
    @Autowired
    GeneratorService generatorService;

    @GetMapping()
    String generator() {
        return prefix + "/list";
    }

    @ResponseBody
    @RequestMapping("/list")
    List<Map<String, Object>> list() {
        List<Map<String, Object>> list = generatorService.list();
        return list;
    }

    ;


    @ResponseBody
    @GetMapping("/table/{tableName}")
    Map<String, Object> get(HttpServletRequest request, HttpServletResponse response, @PathVariable("tableName") String tableName) {
        Map<String, Object> data = generatorService.getTableInfo(tableName);
        return data;
    }

    ;


    @ResponseBody
    @RequestMapping("/code")
    public Result code(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> params) throws IOException {
        byte[] data = generatorService.generatorCode(params);
        ByteArrayEntity bae = new ByteArrayEntity(data);
        long fileId = System.currentTimeMillis();
        RedisUtil.set(RedisConstant.DOWNLOAD_DATA_CONTENT_KEY + fileId, bae, 10);
        return Result.ok(null, String.valueOf(fileId));
    }

    @ResponseBody
    @RequestMapping("/batchCode")
    public Result batchCode(HttpServletRequest request, HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = new String[]{};
        tableNames = JSON.parseArray(tables).toArray(tableNames);
        byte[] data = generatorService.generatorCode(tableNames);
        ByteArrayEntity bae = new ByteArrayEntity(data);
        long fileId = System.currentTimeMillis();
        RedisUtil.set(RedisConstant.DOWNLOAD_DATA_CONTENT_KEY + fileId, bae);
        return Result.ok(null, String.valueOf(fileId));
    }

    @GetMapping("/edit")
    public String edit(Model model) {
        Configuration conf = GenUtils.getConfig();
        Map<String, Object> property = new HashMap<>(16);
        property.put("author", conf.getProperty("author"));
        property.put("email", conf.getProperty("email"));
        property.put("package", conf.getProperty("package"));
        property.put("autoRemovePre", conf.getProperty("autoRemovePre"));
        property.put("tablePrefix", conf.getProperty("tablePrefix"));
        model.addAttribute("property", property);
        return prefix + "/edit";
    }

    @ResponseBody
    @PostMapping("/update")
    Result update(@RequestParam Map<String, Object> map) {
        try {
            PropertiesConfiguration conf = new PropertiesConfiguration("generator.properties");
            conf.setProperty("author", map.get("author"));
            conf.setProperty("email", map.get("email"));
            conf.setProperty("package", map.get("package"));
            conf.setProperty("autoRemovePre", map.get("autoRemovePre"));
            conf.setProperty("tablePrefix", map.get("tablePrefix"));
            conf.save();
        } catch (ConfigurationException e) {
            return Result.error("保存配置文件出错");
        }
        return Result.ok();
    }


    @RequestMapping("/file/{fileId}")
    public void getFile(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileId") String fileId) throws IOException {
        ByteArrayEntity bae = RedisUtil.get(RedisConstant.DOWNLOAD_DATA_CONTENT_KEY + fileId, ByteArrayEntity.class);
        byte[] data = bae.getBytes();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
